<script setup>
  import { onMounted, ref } from 'vue'
  import { http } from '@/utils/http.js'
  import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'
  import { parseTime } from '@/utils/index.js'
  import { useUsercodeStore } from '@/store/usercode.js'
  import Tabbar from '@/components/TabbarCustom.vue'

  // 背包列表\
  const bagGoods = ref([])
  const mergeList = ref([])
  const currentPage = ref(1)
  async function getBagList() {
    const res = await http.request({
      url: '/api/bag/bagList',
      method: 'POST',
      data: {
        page: currentPage.value,
        limit: 10,
        compound: goodsCategary.value,
        type: saleCategary.value,
        launch: currentButton.value,
        status: statueCategory.value,
        is_bidding: 0,
        rule_id: 0,
      },
    })

    // 计算多少天过期
    res.data.forEach((item) => {
      const today = new Date()
      const passtime = new Date(parseTime(item.pass_time))
      const timeDifference = passtime - today
      item.pass_time = Math.floor(timeDifference / (1000 * 60 * 60 * 24))
      item.checked = false
    })
    bagGoods.value = [...bagGoods.value, ...res.data]
    if (currentPage.value == 1) {
      mergeList.value = res.compound_goods
    }

    // if (res.data.address_status == 1) {
    //   uni.utils.toast('背包商品即将自动发货，请填写地址。')
    //   setTimeout(() => {
    //     uni.navigateTo({
    //       url: `/minePage/editaddress/index`,
    //     })
    //   }, 2000)
    // }
  }

  // 去合成
  function goMerge() {
    uni.navigateTo({
      url: '/mergePage/merge/index',
    })
  }

  // 去交易
  function goDeal() {
    uni.navigateTo({
      url: '/transactionPage/transaction/index',
    })
  }

  //折叠展开
  const currentButton = ref(1)
  const clickLimit = ref(true)
  function change(index) {
    if (clickLimit.value) {
      clickLimit.value = false
      allchecked.value = false
      currentButton.value = index
      currentPage.value = 1
      bagGoods.value = []
      getBagList()
      setTimeout(() => {
        clickLimit.value = true
      }, 1200)
    } else {
      uni.utils.toast('让手指放松下吧，请两秒后重试~')
    }
  }
  //选择
  const deliveryList = ref([])
  const allchecked = ref(false)
  function checkedAll() {
    allchecked.value = !allchecked.value
    if (allchecked.value) {
      deliveryList.value = []
      bagGoods.value.forEach((item) => {
        item.checked = true
        deliveryList.value.push(item.id)
      })
    } else {
      bagGoods.value.forEach((item) => {
        item.checked = false
      })
      deliveryList.value = []
    }
  }
  function checkboxChange(e) {
    console.log(e.detail.value)
    if (e.detail.value.length != bagGoods.value.length) {
      allchecked.value = false
    } else {
      allchecked.value = true
    }
    deliveryList.value = e.detail.value
  }

  function goOrder() {
    const userCodeStore = useUsercodeStore()
    if (
      userCodeStore.usercode.token == '' ||
      userCodeStore.usercode.userId == ''
    ) {
      uni.utils.toast('为了让您有更好的体验，请先登录')
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/login/login`,
        })
      }, 2000)
      return
    }
    if (
      userCodeStore.usercode.isAddress == 0 &&
      userCodeStore.usercode.token != ''
    ) {
      uni.utils.toast('为了让您有更好的体验，请先完善物流信息')
      setTimeout(() => {
        uni.navigateTo({
          url: `/minePage/editaddress/index`,
        })
      }, 2000)
      return
    }
    if (deliveryList.value.length == 0) {
      uni.utils.toast('请选择奖品')
      return
    }
    // 创建一个对象，用于存储每个元素出现的次数
    const countMap = ref({})

    // 遍历数组，统计每个元素出现的次数
    // deliveryList.value.forEach((item) => {
    // 	countMap.value[item] = (countMap.value[item] || 0) + 1
    // })

    // // 将统计结果转换为目标格式的数组
    // const result = Object.keys(countMap.value).map((key) => {
    // 	let info = {}
    // 	bagGoods.value.forEach((infoItem) => {
    // 		if (infoItem.goods_id == key) {
    // 			info = infoItem
    // 		}
    // 	})
    // 	console.log(key)
    // 	return {
    // 		goods_id: key,
    // 		num: countMap.value[key],
    // 		img: info ? info.img : null,
    // 		price: info ? info.box_price : null,
    // 	}
    // })
    // console.log(result)
    // const toResult = ref(result)
    uni.navigateTo({
      url: `/mergePage/bagorder/index?info=${encodeURIComponent(
        JSON.stringify(deliveryList.value)
      )}`,
    })
  }

  // 分类弹出
  const categorypopup = ref()
  function categoryPOP() {
    categorypopup.value.open('top')
  }
  const saleCategary = ref('2')
  const goodsCategary = ref('0')
  const statueCategory = ref('1')
  function chooseSale(type) {
    saleCategary.value = type
  }
  function chooseGoods(type) {
    goodsCategary.value = type
  }
  function chooseStatue(type) {
    statueCategory.value = type
  }
  // 重置筛选条件
  function queryReset() {
    saleCategary.value = '2'
    goodsCategary.value = '0'
  }
  // 筛选
  function filter() {
    currentPage.value = 1
    bagGoods.value = []
    getBagList()
    categorypopup.value.close('top')
  }
  // 分类弹出
  const rulespopup = ref()
  function rulesPOP() {
    rulespopup.value.open('top')
  }

  function getMore() {
    allchecked.value = false
    ++currentPage.value
    getBagList()
  }

  onShareAppMessage(() => {
    const userCodeStore = useUsercodeStore()
    const user = userCodeStore.usercode.user
    return {
      title: '奖品进阶，快乐翻倍',
      path: `/pages/home/index?pid=${user}`,
    }
  })
  onShow(() => {
    // uni.hideTabBar()
    currentPage.value = 1
    goodsCategary.value = 0
    saleCategary.value = 2
    bagGoods.value = []
    allchecked.value = false
    currentButton.value = 1
    deliveryList.value = []
    getBagList()
  })
</script>

<template>
  <view class="bag-content">
    <view class="merge">
      <image
        style="width: 344rpx; height: 140rpx"
        src="https://ojqn.wm2177.com/wechat_imgs/bag-merge.png"
        mode=""
        @click="goMerge"
      ></image>
      <image
        style="width: 344rpx; height: 140rpx"
        src="https://ojqn.wm2177.com/wechat_imgs/bag-deal.png"
        mode=""
        @click="goDeal"
      ></image>
      <!-- <view class="merge-title">
				<view class="title"> 热门合成 </view>
				<view class="go-merge" @click="goMerge"> 前去合成> </view>
			</view>
			<view class="merge-content">
				<view
					class="content-item"
					v-for="item in mergeList"
					:key="'merge' + item.id"
				>
					<image
						style="width: 136rpx; height: 136rpx"
						:src="item.compound_img"
						mode=""
					></image>
				</view>
			</view> -->
    </view>
    <view class="filter">
      <view class="filter-left">
        <view class="all" @click="categoryPOP">
          <view style="margin-right: 12rpx; font-size: 28rpx">筛选</view>
          <view class="downaim"> </view>
          <view
            class=""
            style="margin-left: 20rpx; font-size: 22rpx; color: #bbbbbb"
          >
            {{ saleCategary == 2 ? '现货' : '预售' }}—{{
              statueCategory == 1 ? '在库' : '交易中'
            }}
          </view>
        </view>
        <!-- <uni-icons type="info" size="18" @click="rulesPOP"></uni-icons> -->
      </view>
      <view class="filter-right">
        <view :class="{ 'active-view': currentButton == 1 }" @click="change(1)">
          折叠
        </view>
        <view :class="{ 'active-view': currentButton == 2 }" @click="change(2)">
          展开
        </view>
      </view>
    </view>
    <view class="scroll-message">
      <!-- <uni-notice-bar
        :speed="40"
        color="#3d3d3d"
        background-color="#FFFDE7"
        scrollable
        text="赏品默认发货周期为30天，到期后赏品将自动发货至默认收货地址，请留意赏品库存到期时间噢~"
      /> -->
    </view>
    <view class="goods">
      <view class="" v-if="currentButton == 1">
        <scroll-view
          scroll-y="true"
          class="scroll-goods"
          @scrolltolower="getMore"
        >
          <view
            class="goods-item"
            v-for="(item, index) in bagGoods"
            :key="'baggoods' + index"
          >
            <view class="goods-img">
              <image
                v-if="item.rule_img"
                :src="item.rule_img"
                mode="heightFix"
                style="position: absolute; top: 0; left: 0; height: 40rpx"
              ></image>
              <image
                v-if="item.status == 3"
                style="
                  position: absolute;
                  top: 0;
                  left: 0;
                  z-index: 2;
                  width: 160rpx;
                  height: 160rpx;
                "
                src="https://ojqn.wm2177.com/wechat_imgs/dealing.png"
                mode=""
              ></image>
              <image
                style="width: 160rpx; height: 160rpx"
                :src="item.img"
                mode=""
              ></image>
              <view class="presale" style="" v-if="item.goods_type == 1">
                预售
              </view>
            </view>
            <view class="goods-info">
              <view class="goods-title">
                {{ item.goods_name }}
              </view>
              <view class="goods_bottom" style="">
                <view style="font-size: 22rpx; color: #e2e1df">不支持回收</view>
                <view class="bottom-right"> X{{ item.goods_num }} </view>
              </view>

              <!--     <view class="goods-bottom">
                <view class="bottom-left" v-if="item.goods_type == 2">
                  <image
                    style="width: 24rpx; height: 24rpx; margin-right: 6rpx"
                    src="../../static/time.png"
                    mode=""
                  ></image>
                  <text>还有{{ item.pass_time }}天自动发货</text>
                </view>
              </view> -->
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="" v-else-if="currentButton == 2">
        <scroll-view
          scroll-y="true"
          class="scroll-goods-deliver"
          @scrolltolower="getMore"
        >
          <checkbox-group @change="checkboxChange">
            <view
              class="scroll-goods-deliver-item"
              v-for="(item, index) in bagGoods"
              :key="'baggoodstwo' + index"
            >
              <view v-if="item.status == 1 && item.goods_type == 2">
                <checkbox
                  activeBackgroundColor="#7863ff"
                  style="transform: scale(0.8)"
                  :value="item.id"
                  :checked="item.checked"
                />
              </view>
              <view class="goods-info">
                <view class="goods-img">
                  <image
                    class="aaaaaaaaa"
                    v-if="item.rule_img"
                    :src="item.rule_img"
                    mode="heightFix"
                    style="position: absolute; top: 0; left: 0; height: 44rpx"
                  ></image>
                  <image
                    v-if="item.status == 3"
                    style="
                      position: absolute;
                      top: 0;
                      left: 0;
                      z-index: 2;
                      width: 160rpx;
                      height: 160rpx;
                    "
                    src="https://ojqn.wm2177.com/wechat_imgs/dealing.png"
                    mode=""
                  ></image>
                  <image
                    style="width: 160rpx; height: 160rpx"
                    :src="item.img"
                    mode=""
                  ></image>
                  <view class="presale" style="" v-if="item.goods_type == 1">
                    预售
                  </view>
                </view>
                <view class="goods-content">
                  <view class="content-top">
                    {{ item.goods_name }}
                  </view>
                  <view class="" style="font-size: 22rpx; color: #e2e1df">
                    不支持回收
                  </view>
                  <view class="content-bottom">
                    <!-- <view class="bottom-top" v-if="item.goods_type == 2">
                      <image
                        style="width: 24rpx; height: 24rpx"
                        src="../../static/time.png"
                        mode=""
                      ></image>
                      <view style="margin-left: 6rpx"
                        >还有{{ item.pass_time }}天自动发货</view
                      >
                    </view> -->
                    <view class="bottom-price">
                      实付￥{{ item.box_price }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </checkbox-group>
        </scroll-view>
        <view
          class="bottom-goto"
          v-if="statueCategory == 1 && saleCategary == 2"
        >
          <label class="check"
            ><checkbox
              value="all"
              @click="checkedAll"
              :checked="allchecked"
              style="transform: scale(0.8)"
              activeBackgroundColor="#FFE60F"
            />全选</label
          >
          <view class="check-right">
            <view class="total"> 已选:{{ deliveryList.length }} </view>
            <view class="godeliver" @click="goOrder"> 去发货 </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类弹出层 -->
    <uni-popup ref="categorypopup" type="top">
      <view class="categorypopup">
        <view class="title"> 销售类型 </view>
        <view class="category" style="margin-bottom: 60rpx">
          <!-- <view
						@click="chooseSale('0')"
						:class="{ saleactive: saleCategary == '0' }"
						>全部</view
					> -->
          <view
            @click="chooseSale('2')"
            :class="{ saleactive: saleCategary == '2' }"
            >现货</view
          >
          <view
            @click="chooseSale('1')"
            :class="{ saleactive: saleCategary == '1' }"
            >预售</view
          >
        </view>
        <view class="title"> 商品类型 </view>
        <view class="category" style="margin-bottom: 78rpx">
          <view
            @click="chooseGoods('0')"
            :class="{ saleactive: goodsCategary == '0' }"
            >全部</view
          >
          <view
            @click="chooseGoods('2')"
            :class="{ saleactive: goodsCategary == '2' }"
            >普通赏</view
          >
          <view
            @click="chooseGoods('1')"
            :class="{ saleactive: goodsCategary == '1' }"
            >特殊赏</view
          >
        </view>
        <view class="title"> 商品状态 </view>
        <view class="category" style="margin-bottom: 78rpx">
          <view
            @click="chooseStatue('1')"
            :class="{ saleactive: statueCategory == '1' }"
            >在库</view
          >
          <view
            @click="chooseStatue('3')"
            :class="{ saleactive: statueCategory == '3' }"
            >交易中</view
          >
        </view>
        <view class="category-button">
          <view class="reset" @click="queryReset"> 重置 </view>
          <view class="ask" @click="filter"> 确认 </view>
        </view>
      </view>
    </uni-popup>

    <!-- 说明弹出层 -->
    <uni-popup ref="rulespopup" type="bottom">
      <view class="rulespopup">
        <view class="rule-title"> 背包说明 </view>
        <view class="rule-content"> </view>
      </view>
    </uni-popup>
    <Tabbar :current="2"></Tabbar>
  </view>
</template>

<style lang="scss" scoped>
  .bag-content {
    color: #3d3d3d;
    font-weight: 500;
    .merge {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 156rpx;
      padding: 0rpx 20rpx 0 20rpx;
      box-sizing: border-box;
      .merge-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .title {
          font-size: 28rpx;
        }
        .go-merge {
          width: 178rpx;
          height: 48rpx;
          border-radius: 24rpx;
          background-color: #7863ff;
          font-size: 24rpx;
          text-align: center;
          line-height: 48rpx;
          color: #fff;
        }
      }
      .merge-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 18rpx;
        .content-item {
          width: 136rpx;
          height: 136rpx;
          border-radius: 10rpx;
          overflow: hidden;
        }
      }
    }
    .filter {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 11rpx;
      padding: 0 20rpx;
      box-sizing: border-box;
      .filter-left {
        display: flex;
        align-items: center;
        .all {
          display: flex;
          align-items: center;
          margin-right: 22rpx;
        }
        .downaim {
          width: 8rpx;
          height: 8rpx;
          border-bottom: 1px solid #3d3d3d;
          border-right: 1px solid #3d3d3d;
          transform: rotate(45deg);
        }
      }
      .filter-right {
        display: flex;
        align-items: center;
        font-size: 26rpx;
        view {
          width: 82rpx;
          height: 44rpx;
          border-radius: 2rpx;
          background-color: #f5f5f5;
          text-align: center;
          line-height: 44rpx;
          color: #999999;
        }
        .active-view {
          color: #3d3d3d;
          background-color: $all-color;
        }
      }
    }
    .scroll-message {
      margin-top: 11rpx;
      background-color: #fbfaff;
      ::v-deep .uni-noticebar {
        height: 54rpx;
        // margin-top: 18rpx;

        .uni-noticebar__content-text {
          font-size: 20rpx;
        }
      }
    }
    .goods {
      .scroll-goods {
        height: 87vh;
        .goods-item {
          display: flex;
          align-items: center;
          height: 195rpx;
          margin: 0 20rpx;
          padding: 0 30rpx;
          border-bottom: 1px solid #f5f5f5;
          box-sizing: border-box;
          margin-bottom: 30rpx;
          &:last-child {
            border: none;
          }
          .goods-img {
            position: relative;
            width: 160rpx;
            height: 160rpx;
            margin-right: 18rpx;
            border-radius: 8rpx;
            overflow: hidden;
            flex-shrink: 0;
            .presale {
              position: absolute;
              bottom: 0;
              right: 0;
              z-index: 2;
              width: 66rpx;
              height: 32rpx;
              background-color: rgba(0, 0, 0, 0.5);
              border-radius: 0rpx 0rpx 8rpx 0rpx;
              font-size: 22rpx;
              color: #fff;
              line-height: 32rpx;
              text-align: center;
            }
          }
          .goods-info {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            width: 100%;
            height: 160rpx;
            // background-color: pink;
            .goods-title {
              // height: 74rpx;
              width: 100%;
              font-size: 26rpx;
              display: -webkit-box;
              -webkit-line-clamp: 2; /* 限制为两行 */
              -webkit-box-orient: vertical;
              overflow: hidden; /* 隐藏超出部分 */
              text-overflow: ellipsis; /* 超出部分用省略号表示 */
              white-space: normal; /* 允许换行 */
              /* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
            }
            .goods_bottom {
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
            .goods-bottom {
              display: flex;
              align-items: center;
              justify-content: space-between;
              .bottom-left {
                display: flex;
                align-items: center;
                color: #f58300;
                font-size: 20rpx;
              }
              .bottom-right {
                font-size: 24rpx;
              }
            }
          }
        }
      }
      .scroll-goods-deliver {
        height: 60vh;
        .scroll-goods-deliver-item {
          display: flex;
          align-items: center;
          height: 195rpx;
          margin: 0 20rpx;
          padding-left: 22rpx;
          border-bottom: 1px solid #f5f5f5;
          box-sizing: border-box;
          margin-bottom: 30rpx;
          &:last-child {
            border: none;
          }
          ::v-deep uni-checkbox .uni-checkbox-input {
            border-radius: 50% !important;
          }
          ::v-deep checkbox .wx-checkbox-input {
            border-radius: 50% !important;
            color: #3d3d3d !important;
          }

          ::v-deep checkbox .wx-checkbox-input.wx-checkbox-input-checked {
            color: #3d3d3d;
            background: #ffe60f;
          }

          ::v-deep .wx-checkbox-input.wx-checkbox-input-checked {
            border-color: #ffe60f !important;
          }
          .goods-info {
            width: 100%;
            display: flex;
            align-items: center;
            .goods-img {
              position: relative;
              width: 160rpx;
              height: 160rpx;
              margin-right: 17rpx;
              overflow: hidden;
              flex-shrink: 0;

              .presale {
                position: absolute;
                bottom: 0;
                right: 0;
                z-index: 2;
                width: 66rpx;
                height: 32rpx;
                background-color: rgba(0, 0, 0, 0.5);
                border-radius: 0rpx 0rpx 8rpx 0rpx;
                font-size: 22rpx;
                color: #fff;
                line-height: 32rpx;
                text-align: center;
              }
            }
            .goods-content {
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              width: 100%;
              height: 160rpx;
              .content-top {
                font-size: 26rpx;

                // height: 74rpx;
                width: 100%;
                display: -webkit-box;
                -webkit-line-clamp: 2; /* 限制为两行 */
                -webkit-box-orient: vertical;
                overflow: hidden; /* 隐藏超出部分 */
                text-overflow: ellipsis; /* 超出部分用省略号表示 */
                white-space: normal; /* 允许换行 */
                /* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
              }
              .content-bottom {
                .bottom-top {
                  display: flex;
                  align-items: center;
                  margin-bottom: 6rpx;
                  font-size: 20rpx;
                  color: #f58300;
                }
                .bottom-price {
                  font-size: 24rpx;
                }
              }
            }
          }
        }
      }
    }
    .bottom-goto {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: fixed;
      bottom: 200rpx;
      left: 0;
      width: 100%;
      padding: 0 26rpx;
      height: 112rpx;
      box-sizing: border-box;

      ::v-deep uni-checkbox .uni-checkbox-input {
        border-radius: 50% !important;
      }
      ::v-deep checkbox .wx-checkbox-input {
        border-radius: 50% !important;
        color: #3d3d3d !important;
      }

      ::v-deep checkbox .wx-checkbox-input.wx-checkbox-input-checked {
        color: #3d3d3d;
        background: $all-color;
      }

      ::v-deep .wx-checkbox-input.wx-checkbox-input-checked {
        border-color: $all-color !important;
      }
      .check {
        font-size: 26rpx;
      }
      .check-right {
        display: flex;
        align-items: center;
        .total {
          margin-right: 44rpx;
          font-size: 26rpx;
        }
        .godeliver {
          height: 70rpx;
          width: 162rpx;
          border-radius: 35rpx;
          background-color: $all-color;
          text-align: center;
          line-height: 70rpx;
          font-size: 28rpx;
          color: #3d3d3d;
          font-weight: 600;
        }
      }
    }
    .categorypopup {
      height: 806rpx;
      padding: 24rpx;
      box-sizing: border-box;
      background-color: #fff;
      .title {
        margin-bottom: 28rpx;
        font-size: 32rpx;
        font-weight: 700;
      }
      .category {
        display: flex;
        align-items: center;
        view {
          width: 158rpx;
          height: 72rpx;
          margin-right: 24rpx;
          box-sizing: border-box;
          border: 2rpx solid #f4f4f4;
          color: #aaaaaa;
          font-size: 28rpx;
          text-align: center;
          line-height: 72rpx;
        }
        .saleactive {
          background-color: $all-color;
          color: #3d3d3d;
          font-weight: 600;
          // border-color: $all-color;
        }
      }
      .category-button {
        display: flex;
        align-items: center;
        justify-content: space-between;
        view {
          width: 328rpx;
          height: 102rpx;
          font-size: 32rpx;
          line-height: 102rpx;
          text-align: center;
        }
        .reset {
          background-color: #f5f6fa;
        }
        .ask {
          background-color: $all-color;
          color: #3d3d3d;
          font-weight: 600;
        }
      }
    }
    ::v-deep .uni-popup__wrapper-box {
      padding: 0;
    }
    .rulespopup {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 1150rpx;
      border-radius: 40rpx 40rpx 0 0;
      background: linear-gradient(
        162deg,
        #e9e6fb 3%,
        #e9e7fb 10%,
        #f9f9ee 67%,
        #ffffff 104%
      );
      .rule-title {
        width: 234rpx;
        margin: 36rpx 0 48rpx 0;
        box-sizing: border-box;
        background: url('https://ojqn.wm2177.com/wechat_imgs/wx/rule-title.png')
          no-repeat;
        background-size: 100%;
        background-position: 0 16rpx;
        font-size: 44rpx;
        font-weight: 700;
        text-align: center;
      }
      .rule-content {
        width: 708rpx;
        height: 982rpx;
        border-radius: 26rpx;
        background-color: #fff;
      }
    }
  }
</style>
